package fun.ltool.core.excel.convert;

import fun.ltool.core.exceptions.ExcelException;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 默认转换器
 *
 * @author huangrongsong
 * @since 1.3
 */
public class DefaultExcelTypeConverter implements ExcelTypeConverter<Object> {

    @Override
    public Object convert(Object value, Class<?> fieldType) {
        if (value == null) {
            return null;
        }
        try {
            // 基础类型转换
            if (fieldType == String.class) {
                return value.toString();
            } else if (fieldType == int.class || fieldType == Integer.class) {
                return Integer.parseInt(value.toString());
            } else if (fieldType == double.class || fieldType == Double.class) {
                return Double.parseDouble(value.toString());
            } else if (fieldType == boolean.class || fieldType == Boolean.class) {
                return Boolean.parseBoolean(value.toString());
            } else if (fieldType == float.class || fieldType == Float.class) {
                return Float.parseFloat(value.toString());
            } else if (fieldType == long.class || fieldType == Long.class) {
                return Long.parseLong(value.toString());
            } else if (fieldType == short.class || fieldType == Short.class) {
                return Short.parseShort(value.toString());
            } else if (fieldType == byte.class || fieldType == Byte.class) {
                return Byte.parseByte(value.toString());
            } else if (fieldType == char.class || fieldType == Character.class) {
                return value.toString().charAt(0);
            }
            // BigDecimal
            else if (fieldType == BigDecimal.class) {
                return new BigDecimal(value.toString());
            }
            // 时间类型转换
            else if (fieldType == LocalDate.class) {
                return LocalDate.parse(value.toString());
            } else if (fieldType == LocalDateTime.class) {
                return LocalDateTime.parse(value.toString());
            } else if (fieldType == LocalTime.class) {
                return LocalTime.parse(value.toString());
            }
        } catch (Exception e) {
            throw new ExcelException("值类型：" + value.getClass().getName() + " 转换目标类型: " + fieldType.getName() + ",失败", e);
        }
        return value;
    }
}
